package interfaces

import (
	"deploy/interfaces/db"
	"deploy/schema"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
)

////
//r.GET("/deploy/instancegroup",)
////  服务器分组的增删改查
//r.GET("/deploy/instancegroup/:groupid",)	 // 查详情
//r.POST("/deploy/instancegroup/:groupid",)   //修改
//r.POST("/deploy/instancegroup")   // 增
//r.DELETE("/deploy/instancegroup/:groupid")  // 删除
////r.GET("/deploy/resource")    //  查找可用的组织服务树、tag信息 取消

//  获取分组信息
func (s *Server)GetGroupsEach(c *gin.Context) {
	result := schema.Result{}
	defer func() {
		if err := recover(); err != nil {
			if result.Code==0{
				result.Code = 400
			}
			result.Err = fmt.Sprintf("%s",err)
		}
		c.JSON(result.Code,result)
	}()
	// 2 arg
	pageSize := c.Query("page_size")
	pageNum := c.Query("page_num")
	server := c.Query("server")
	ps,err:=strconv.Atoi(pageSize)
	if err != nil{
		log.Println("GetGroupsEach 查询服务器部署详情异常：",err)
		result.Code=400
		panic("page_size参数异常")
	}
	pn,err := strconv.Atoi(pageNum)
	if err != nil{
		log.Println("GetGroupsEach 查询服务器部署详情异常：",err)
		result.Code=400
		panic("page_num参数异常")
	}
	groups:= []db.Group{}
	if server ==""{
		err = s.Db.GetGroups(ps,pn,&groups)
		}else {
		err = s.Db.GetGroupByServers(ps,pn,server,&groups)
	}
	if err !=nil{
		log.Printf("查询实例分组时发生错误，page_size:%d page_num:%d server:%v err:%v",ps,pn,server,err)
		panic("查询实例分组异常:"+err.Error())
	}
	datas := []schema.SchemaGroupEach{}
	for _,i := range groups{
		log.Println(i)
		each := schema.SchemaGroupEach{
			Id: i.ID,
			GroupName: i.GroupName,
			Description: i.Description,
			ServerName: i.ServerName,
			CreateAt: i.CreatedAt,
			UpdateAt: i.UpdatedAt,
			User:i.User,
			}
		all:=[]string{}
		offline := []string{}
		for _,in := range i.Instances{
			all=append(all, in.HostName)
			if ! in.IsOnline{
				offline=append(offline, in.HostName)
			}
		}
		each.InstanceList=all
		each.OfflineList=offline
		datas = append(datas, each)
	}
	result.Data=datas
	result.Code = http.StatusOK
}

//  获取分组信息
func (s *Server)GetAllroups(c *gin.Context) {
	result := schema.Result{}
	defer func() {
		if err := recover(); err != nil {
			if result.Code==0{
				result.Code = 400
			}
			result.Err = fmt.Sprintf("%s",err)
		}
		c.JSON(result.Code,result)
	}()
	// 2 arg

	groups:= []db.Group{}

	err := s.Db.GetAllGroups(&groups)
	if err != nil {
		result.Code=500
		result.Err = fmt.Sprintf("查询分组数据失败")
		return
	}

	datas := []schema.SchemaGroupEach{}
	for _,i := range groups{
		log.Println(i)
		each := schema.SchemaGroupEach{
			Id: i.ID,
			GroupName: i.GroupName,
			Description: i.Description,
			ServerName: i.ServerName,
			CreateAt: i.CreatedAt,
			UpdateAt: i.UpdatedAt,
			User:i.User,
		}
		all:=[]string{}
		offline := []string{}
		for _,in := range i.Instances{
			all=append(all, in.HostName)
			if ! in.IsOnline{
				offline=append(offline, in.HostName)
			}
		}
		each.InstanceList=all
		each.OfflineList=offline
		datas = append(datas, each)
	}
	result.Data=datas
	result.Code = http.StatusOK
}

// 获取一个分组详细的信息
//func (s *Server)GetGroupDetail(c *gin.Context) {
//	result := schema.Result{}
//	defer func() {
//		if err := recover(); err != nil {
//			if result.Code==0{
//				result.Code = 400
//			}
//			result.Err = fmt.Sprintf("%s",err)
//		}
//		c.JSON(result.Code,result)
//	}()
//}

//  修改一个分组
func (s *Server)UpdateGroupDetail(c *gin.Context) {
	result := schema.Result{}
	defer func() {
		if err := recover(); err != nil {
			if result.Code==0{
				result.Code = 400
			}
			result.Err = fmt.Sprintf("%s",err)
		}
		c.JSON(result.Code,result)
	}()
	// 2、参数处理
	req := schema.SchemaCreateGroup{}
	groupid := c.Param("groupid")
	gid ,err := strconv.Atoi(groupid)
	if err !=nil {
		log.Println("groupid 异常：",err)
		result.Code=400
		panic("参数异常")
	}
	err = c.BindJSON(&req)
	if err!=nil{
		log.Println(err.Error())
		panic("参数错误")
	}
	// 3、数据校验
	// 检测此id是否存在
	g1 := db.Group{}
	err = s.Db.GetGroupByGroupId(gid,&g1)
	if err != nil{
		log.Printf("查询group_name是 %s的组出错：%v\n",req.GroupName,err.Error())
	}
	if g1.ID==0{
		log.Printf("在修改实例分组时，未查找到%d 实例分组\n",gid)
		result.Code=400
		panic("未查找到这个实例分组")
	}
	log.Println("数据库中查找到了实例分组")
	//
	instances :=[]db.Instance{}
	errInstances :=[]string{}
	for _,i := range req.InstanceList{
		var linstance db.Instance
		err =s.Db.GetInstanceByHostname(i,&linstance)
		if err != nil{
			log.Printf("查询实例%s异常：%v\n",i,err)
			errInstances = append(errInstances, i)
		}else {
			instances = append(instances, linstance)
		}
	}
	// 检测是否已经在数据库中有同名的分组
	g := db.Group{}
	err = s.Db.GetGroupByName(req.GroupName,&g)
	if err != nil{
		log.Printf("查询group_name是 %s的组出错：%v\n",req.GroupName,err.Error())
	}
	if g.ID!=0 && int(g.ID) != gid{
		log.Printf("在更新的实例分组时，组名%s已经存在\n",req.GroupName)
		result.Code=400
		panic("已存在同名的实例分组")
	}
	log.Println("数据库中不存在同名实例分组，进行更新")
	updateGroup:= db.Group{
		GroupName: req.GroupName,
		ServerName: req.ServerName,
		Description: req.Description,
		User: req.User,
		Instances: instances,
	}

	err = s.Db.UpdateGroupById(gid,&updateGroup)
	if err !=nil{
		log.Println("更新实例分组出现异常：",err)
		panic(err)
	}
	log.Println("更新实例分组成功")
	result.Code=200
	result.Msg="更新实例分组成功"
}
// 新增一个分组
func (s *Server)AddGroupDetail(c *gin.Context) {
	data := schema.SchemaCreateGroupResult{}
	result := schema.Result{Data: data}
	defer func() {
		if err := recover(); err != nil {
			if result.Code==0{
				result.Code = 400
			}
			result.Err = fmt.Sprintf("%s",err)
		}
		c.JSON(result.Code,result)
	}()
	// 2、参数处理
	req := schema.SchemaCreateGroup{}
	err := c.BindJSON(&req)
	if err!=nil{
		log.Println(err.Error())
		panic("参数错误")
	}
	log.Println(req)
	// 3、数据校验
	instances :=[]db.Instance{}
	errInstances :=[]string{}
	for _,i := range req.InstanceList{
		var linstance db.Instance
		err =s.Db.GetInstanceByHostname(i,&linstance)
		if err != nil{
			log.Printf("查询实例%s异常：%v\n",i,err)
			errInstances = append(errInstances, i)
		}else {
			instances = append(instances, linstance)
		}
	}
	// 检测是否已经在数据库中有同名的分组
	g := db.Group{}
	err = s.Db.GetGroupByName(req.GroupName,&g)
	if err != nil{
		log.Printf("查询group_name是 %s的组出错：%v\n",req.GroupName,err.Error())
	}
	if g.ID!=0{
		log.Printf("在创建新的实例分组时，组名%s已经存在\n",req.GroupName)
		result.Code=400
		panic("已存在同名的实例分组")
	}
	log.Println("数据库中不存在同名实例分组")
	// 当实例数量大于0时再创建新的组
	if len(instances) >0{
		newgroup:= db.Group{
			GroupName: req.GroupName,
			ServerName: req.ServerName,
			Description: req.Description,
			User: req.User,
			Instances: instances,
		}
		err = s.Db.NewGroup(&newgroup)
		if err != nil{
			msg := fmt.Sprintf("创建新的实例分组异常：%v",err)
			log.Println(msg)
			panic(msg)
		}
		// 实例名称全正确时
		if len(errInstances) == 0{
			result.Msg="创建实例分组成功"
			result.Code=200
			return
		}
		result.Msg="创建实例分组部分成功"
		return
	}
	result.Err="实例名称检测异常，请确认"
	result.Code=404
}

//  删除一个分组
func (s *Server)DeleteGroupDetail(c *gin.Context) {
	result := schema.Result{}
	defer func() {
		if err := recover(); err != nil {
			if result.Code==0{
				result.Code = 400
			}
			result.Err = fmt.Sprintf("%s",err)
		}
		c.JSON(result.Code,result)
	}()
	groupid := c.Param("groupid")
	gid ,err := strconv.Atoi(groupid)
	if err !=nil {
		log.Println("groupid 异常：",err)
		result.Code=400
		panic("参数异常")
	}
	err = s.Db.DeleteGroupById(gid)
	if err !=nil{
		log.Println("删除实例分组异常：",err.Error())
		result.Code=502
		panic(err)
	}
	log.Println("删除实例分组成功")
	result.Msg="删除实例分组成功"
}
